package com.itheima.springbootwebtlias.service.impl;

import com.itheima.springbootwebtlias.anno.LogOperation;
import com.itheima.springbootwebtlias.anno.MyLog;
import com.itheima.springbootwebtlias.commons.CurrentHolder;
import com.itheima.springbootwebtlias.exception.DeletionIsNotAllowed;
import com.itheima.springbootwebtlias.mapper.DeptMapper;
import com.itheima.springbootwebtlias.mapper.EmpMapper;
import com.itheima.springbootwebtlias.pojo.Dept;
import com.itheima.springbootwebtlias.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


/**
 * 部门业务层实现类：处理部门相关业务逻辑
 */
@Slf4j
@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;


    //查询所有部门列表的业务功能方法
    @Override
    public List<Dept> selectAll() {
        // 获取当前起始时间
        //LocalDateTime startTime = LocalDateTime.now();

        // 1.调用持久层Mapper,查询部门列表
        List<Dept> depts = deptMapper.selectAll();

        // 获取当前结束时间
        //LocalDateTime endTime = LocalDateTime.now();

        // 统计耗时
        //System.out.println("selectAll耗时:" + (endTime.getNano() - startTime.getNano()));

        // 2.返回查询结果
        return depts;
    }

    //根据id删除部门业务功能方法
    @LogOperation
    @Override
    @MyLog
    public void removeById(Integer id){
        //0.查询当前部门下是否存在员工
        //1.如果存在员工，则不允许删除
        Integer count = empMapper.selectByDeptId(id);
        if(count != 0){
            // 存在员工，不允许删除
            throw new DeletionIsNotAllowed("当前部门存在员工，不允许删除");
        }

        //2.调用持久层Mapper,删除指定部门
        deptMapper.removeById(id);
    }

    //添加部门业务功能方法
    @LogOperation
    @Override
    public void saveDept(Dept dept){
        log.info("service savedept,当前线程：{}, {}",Thread.currentThread().getName(), CurrentHolder.getCurrentId());

        //1.补充基础信息：创建时间，更新时间
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        //2.调用持久层Mapper，保存部门
        deptMapper.saveDept(dept);
    }

    //根据id查询部门业务功能方法
    @Override
    public Dept findById(int id) {
        //1.调用持久层Mapper，查询指定部门
        return deptMapper.selectById(id);

    }

    //更新部门业务功能方法
    @LogOperation
    @Override
    public void update(Dept dept) {
        //1.同步更新时间
        dept.setUpdateTime(LocalDateTime.now());

        //2.调用持久层Mapper，更新部门
        deptMapper.update(dept);
    }
}
